package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 *
 * @author syl
 * @date 2025-10-20
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void alertFilter() {

        // 查询所有规则
        List<AlertRule> ruleList = this.list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus,1));
        if(CollUtil.isEmpty(ruleList)){
            return;
        }
        // 查询所有设备上报的数据
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if(CollUtil.isEmpty(values)){
            return;
        }


        List<DeviceData> deviceDataList = new ArrayList<>();
        // 做格式化处理  把数据放到一个大集合中
        for (Object value : values) {
            // [{"id":25863,"deviceName":"老陶床位上的设备202-1","i
            List<DeviceData> deviceDataList1 = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(deviceDataList1);
        }

        alertFilterCount = 1;
        // 一条一条的数据处理
        for (DeviceData deviceData : deviceDataList) {
            // 开始一条一条的处理
            System.out.println("-----------"+deviceData);
            alterFilter(deviceData);
        }


    }

    int alertFilterCount = 1;

    private void alterFilter(DeviceData deviceData) {

        log.info("进入到alterFilter方法的次数："+alertFilterCount);
        alertFilterCount++;
        // 举例：查询心率  对所有设备
        //    产品key  functuonId   iotId -1
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getProductKey, deviceData.getProductKey());
        queryWrapper1.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getIotId, -1);
        queryWrapper1.eq(AlertRule::getStatus, 1);
        List<AlertRule> ruleList1 = this.list(queryWrapper1);

        // 举例：查询心率  指定设备   老陶的设备
        // 产品key  functuonId   iotId 老陶的设备Id
        LambdaQueryWrapper<AlertRule> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AlertRule::getProductKey, deviceData.getProductKey());
        queryWrapper2.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper2.eq(AlertRule::getIotId, deviceData.getIotId());
        queryWrapper2.eq(AlertRule::getStatus, 1);
        List<AlertRule> ruleList2 = this.list(queryWrapper2);

        // 合并两个集合
        Collection<AlertRule> ruleList = CollUtil.addAll(ruleList1, ruleList2);
        if(CollUtil.isEmpty(ruleList)){
            return;
        }
        deviceDataAlarmHandlerCount=1;
        for (AlertRule alertRule : ruleList) {
            // 准备校验
            deviceDataAlarmHandler(alertRule, deviceData);
        }


    }

    @Autowired
    private ScriptEngine scriptEngine;

    int deviceDataAlarmHandlerCount = 1;

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {

        log.info("进入到deviceDataAlarmHandler方法的次数："+deviceDataAlarmHandlerCount);
        deviceDataAlarmHandlerCount++;

        log.info("开始第一层的校验");

        String period = alertRule.getAlertEffectivePeriod();
        String[] periods = period.split("~");
        LocalTime startTime = LocalTime.parse(periods[0]);
        LocalTime endTime = LocalTime.parse(periods[1]);

        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();

        //alarmTime startTime         endTime  alarmTime
        if (alarmTime.isBefore(startTime)||alarmTime.isAfter(endTime)) {
            return;
        }
        String alertCountKey=  CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+alertRule.getFunctionId()+alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId()+alertRule.getId();


        log.info("开始第二层的校验");

        String expresstion = deviceData.getDataValue() + alertRule.getOperator() +  alertRule.getValue();

        Boolean isReach = false;
        try {
            isReach = (Boolean) scriptEngine.eval(expresstion);
        } catch (ScriptException e) {
            e.printStackTrace();
            //isReach = false;
        }

        if(!isReach){

            redisTemplate.delete(alertCountKey);  //从0开始数数
            return;
        }

        log.info("开始第三层的校验");
        //  获取Redis中是否有沉默周期
        Boolean isHaveSlient = redisTemplate.hasKey(slientKey);

        if(isHaveSlient){ //有沉默周期
            return;
        }

        log.info("开始第四层的校验");
       // 产品+设备+属性名+规则
        Long alertCount = redisTemplate.boundValueOps(alertCountKey).increment();


        if(alertCount>=alertRule.getDuration()){
            log.info("可以报警了..................................");
            redisTemplate.delete(alertCountKey); //删除报警次数  从0开始数数

            redisTemplate.boundValueOps(slientKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
            // 插入报警数据
            insertAlertData(alertRule, deviceData);
        }


    }

    // alert:
    // deviceMaintainerRole
    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole; //行政
    @Value("${alert.managerRole}")
    private String managerRole; //超级管理员

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IAlertDataService alertDataService;

    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
          // 判断是否为老人数据
        // location_type          int                          null comment '位置类型 0：随身设备 1：固定设备  烟雾报警器+睡眠监测带',


        List<Long> userIds = new ArrayList<>();

        if (deviceData.getLocationType().equals(0)) {
           // 根据老人找护理员
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());

        }else{
            // physical_location_type int                          null comment '物理位置类型 0楼层 1房间 2床位',
            if(deviceData.getPhysicalLocationType().equals(1)){
                // 固定设备报警找行政
                // 根据行政这个角色找人
               userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            }else if(deviceData.getPhysicalLocationType().equals(2)){
               userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        // 查询超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);

        Collection<Long> collection = CollUtil.addAll(userIds, adminIds);

        userIds = CollUtil.distinct(collection); //去重


        List<AlertData> alertDataList = new ArrayList<>();

        for (Long userId : userIds) {
            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());
            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());
            // 报警原因，格式：功能名称+运算符+阈值+持续周期+沉默周期
            alertData.setAlertReason(deviceData.getFunctionId()+alertRule.getOperator()+alertRule.getValue()+alertRule.getDuration()+alertRule.getAlertSilentPeriod());
            // alertData.setProcessingResult();
            // alertData.setProcessorId();
            // alertData.setProcessorName();
            // alertData.setProcessingTime();
            alertData.setType(deviceData.getLocationType());  // 报警数据类型，0：老人异常数据，1：设备异常数据
            alertData.setStatus(0); //状态，0：待处理，1：已处理
            alertData.setUserId(userId);
            alertDataList.add(alertData);
        }
        alertDataService.saveBatch(alertDataList);

        websocketNotity(alertDataList.get(0), alertRule, userIds);


    }

    @Autowired
    private WebSocketServer webSocketServer;

    private void websocketNotity(AlertData alertData, AlertRule alertRule, List<Long> userIds) {


        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);

        webSocketServer.sendMessageToConsumer(alertNotifyVo,userIds);
    }

}
